package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import entities.User;

import cmput391.src.queries.*;

/**
 * Servlet implementation class AddRecord
 */
@WebServlet("/AddRecord")
public class AddRecord extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static int recordID = 1;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddRecord() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Map<String, String> messages = new HashMap<String, String>();
		request.setAttribute("messages", messages);
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		try {

			security = new SecurityQueries(dbConnect.getConnection());
			UserManagementQueries umq = new UserManagementQueries(dbConnect.getConnection(), security);				
			
			/* Validate the Patient Name field */

			//Make sure the patient name isn't blank.
			String patient_name = (request.getParameter("patient_name")).trim();
			if(patient_name.equals("")) {
				messages.put("new_record_msg", "<span class=\"message error\">Patient name is required.</span>");
				request.getRequestDispatcher("addRecord.jsp").forward(request, response);
				return;
			}
			
			//Make sure the patient exists.
			try {
				umq.retrieveUserData(patient_name);
			} catch (SQLException e) {
				messages.put("new_record_msg", "<span class=\"message error\">This patient does not exist.</span>");
				request.getRequestDispatcher("addRecord.jsp").forward(request, response);
				return;
			}

			
			/* Validate the Doctor Name field */
			
			//Make sure the doctor's name isn't blank
			String doctor_name = (request.getParameter("doctor_name")).trim();
			if(doctor_name.equals("")) {
				messages.put("new_record_msg", "<span class=\"message error\">Doctor name is required.</span>");
				request.getRequestDispatcher("addRecord.jsp").forward(request, response);
				return;
			}			
			
			//Make sure doctor is one of the patient's family doctors.
			ArrayList<String> doctorList = umq.retrieveDoctorNames(patient_name);
			if(!doctorList.contains(doctor_name)) {
				messages.put("new_record_msg", "<span class=\"message error\">Invalid doctor. The patient does not see this doctor.</span>");
				request.getRequestDispatcher("addRecord.jsp").forward(request, response);
				return;				
			}
			
			/* Validate the Radiologist Name field */
			
			//Make sure the radiologist's name isn't blank
			String radiologist_name = (request.getParameter("radiologist_name")).trim();
			if(radiologist_name.equals("")) {
				messages.put("new_record_msg", "<span class=\"message error\">Radiologist name is required.</span>");
				request.getRequestDispatcher("addRecord.jsp").forward(request, response);
				return;
			}			
			
			//Make sure the selected person really is a radiologist
			try {
				User radiologist = umq.retrieveUserData(radiologist_name);
				if(!radiologist.getUserClass().equals("r")) {
					messages.put("new_record_msg", "<span class=\"message error\">This person is not a radiologist.</span>");
					request.getRequestDispatcher("addRecord.jsp").forward(request, response);		
					return;
				}
			} catch (SQLException e) {
				messages.put("new_record_msg", "<span class=\"message error\">This radiologist does not exist.</span>");
				request.getRequestDispatcher("addRecord.jsp").forward(request, response);
				return;
			}			
					
			DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
			java.util.Date pd = df.parse((request.getParameter("prescribing_date")).trim());
			java.util.Date td = df.parse((request.getParameter("test_date")).trim());
			
			java.sql.Date prescribing_date = new java.sql.Date(pd.getTime());
			java.sql.Date testing_date = new java.sql.Date(td.getTime());			
			
			UploadQueries upq = new UploadQueries(dbConnect.getConnection(), security);
			upq.createRadRecord(
					recordID, 
					(request.getParameter("patient_name")).trim(), 
					(request.getParameter("doctor_name")).trim(), 
					(request.getParameter("radiologist_name")).trim(), 
					(request.getParameter("test_type")).trim(), 
					prescribing_date, 
					testing_date, 
					(request.getParameter("diagnosis")).trim(), 
					request.getParameter("description")
			);
			recordID++;
		
			
			messages.put("new_record_msg", "<span class=\"message success\">Record Added.</span>");
			request.getRequestDispatcher("addRecord.jsp").forward(request, response);				
				
		} catch (SQLException e) {
			messages.put("new_record_msg", "<span class=\"message error\">Record could not be added.</span>");
			request.getRequestDispatcher("addRecord.jsp").forward(request, response);				
			e.printStackTrace();
		} catch (InstantiationException e) {
			messages.put("new_record_msg", "<span class=\"message error\">Record could not be added.</span>");
			request.getRequestDispatcher("addRecord.jsp").forward(request, response);	
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			messages.put("new_record_msg", "<span class=\"message error\">Record could not be added.</span>");
			request.getRequestDispatcher("addRecord.jsp").forward(request, response);	
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			messages.put("new_record_msg", "<span class=\"message error\">Record could not be added.</span>");
			request.getRequestDispatcher("addRecord.jsp").forward(request, response);	
			e.printStackTrace();
		} catch (ParseException e) {
			messages.put("new_record_msg", "<span class=\"message error\">Invalid date entered.</span>");
			request.getRequestDispatcher("addRecord.jsp").forward(request, response);	
			e.printStackTrace();
		} finally {
			dbConnect.disconnect();
		}
		
	}

}
